package com.example.redisson.service.impl;

import com.example.redisson.service.TestLockService;
import com.example.redisson.util.RedisLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class TestLockServiceImpl implements TestLockService {
    /** 锁测试共享变量 */
    private Integer lockCount = 10;

    /** 无锁测试共享变量 */
    private Integer count = 10;
    /** 加锁测试 */
    @Override
    public void testLockCount() {
        String lockKey = "lock-test";
        try {
            // 加锁，设置超时时间2s
            RedisLockUtil.lock(lockKey, 2, TimeUnit.SECONDS);
            lockCount--;
            log.info("lockCount值：" + lockCount);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            // 释放锁
            RedisLockUtil.unlock(lockKey);
        }
    }

    /** 无锁测试 */
    @Override
    public void testCount() {
        count--;
        log.info("count值：" + count);
    }
}
